"use strict";

/*http://toddmotto.com/a-comprehensive-dive-into-nodelists-arrays-converting-nodelists-and-understanding-the-dom/*/

var app = angular.module("App", ["ngRoute", "ngSanitize", "ngMaterial", "ngAnimate", "ui.bootstrap"]);

app.run(["$rootScope", "$location", "$window", "$notify", "$templateCache", "$token", function ($rootScope, $location, $window, $notify, $templateCache, $token) {

    //gestion du cache de html5
    window.applicationCache.addEventListener("updateready", function (e) {
        if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
            $templateCache.removeAll();
            window.applicationCache.swapCache();
            window.applicationCache.update();
            window.location.reload();
        }
    }, false);

    $rootScope.$on("$routeChangeStart", function (event, next, current) {
        $token.get().then(function () {
            $rootScope.previousRoute = current;
        }, function () {
            $location.path("/login");
        });
    });
} ]);

app.config(["$routeProvider", "$locationProvider", function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode = true;
    $routeProvider.
        when("/", {
            templateUrl: "/admin/partials/app.html",
            controller: "AppCtrl"
        }).
        when("/login", {
            templateUrl: "/app/partials/login.html",
            controller: "LoginCtrl"
        }).
        when("/user/create", {
            templateUrl: "/admin/partials/user.edit.html",
            controller: "UserEditorCtrl"
        }).
        when("/user/edit/:id", {
            templateUrl: "/admin/partials/user.edit.html",
            controller: "UserEditorCtrl"
        }).
        when("/shop/create", {
            templateUrl: "/admin/partials/shop.edit.html",
            controller: "ShopEditorCtrl"
        }).
        when("/shop/edit/:id", {
            templateUrl: "/admin/partials/shop.edit.html",
            controller: "ShopEditorCtrl"
        }).
        otherwise({
            redirectTo: '/'
        });
} ]);

app.controller("AppCtrl", ["$scope", "$rootScope", "$mdSidenav", "connectAdmin", function ($scope, $rootScope, $mdSidenav, connectAdmin) {
    $scope.viewClass = "app";

    $scope.selectedIndex = 0;

    $scope.next = function () {
        $scope.selectedIndex = Math.min($scope.selectedIndex + 1, 2);
    };

    $scope.previous = function () {
        $scope.selectedIndex = Math.max($scope.selectedIndex - 1, 0);
    };

    $scope.openMenu = function () {
        $mdSidenav('left').toggle();
    };

    $scope.disconnect = function () {
        connectAdmin.disconnect();
    };
} ]);

app.controller("LoginCtrl", ["$scope", "connectAdmin", function ($scope, connectAdmin) {
    $scope.pageClass = "login";
    $scope.model = {
        login: "",
        password: ""
    };

    $scope.validate = function () {
        return connectAdmin.connect($scope.model);
    };
} ]);

app.controller("UserEditorCtrl", ["$window", "$scope", "$route", "googleGeocode", "appUserEditor", "appUserCreator", "connectAdmin", "$mdSidenav", function ($window, $scope, $route, googleGeocode, appUserEditor, appUserCreator, connectAdmin, $mdSidenav) {
    $scope.viewClass = "user";

    var userId = $route.current.params.id;

    if(userId) $scope.user = appUserEditor.get(userId);
    else $scope.user = appUserCreator;
    $scope.user.init().then(function(){
        $scope.locationText = $scope.user.data.location.address;
    });

    $scope.back = function () {
        $window.history.back();
    };

    $scope.getLocation = function (val) {
        return googleGeocode.getLocations(val);
    };

    $scope.openMenu = function () {
        $mdSidenav('left').toggle();
    };

    $scope.disconnect = function () {
        connectAdmin.disconnect();
    };
} ]);

app.controller("UsersCtrl", ["$scope", "appUsers", "connectAdmin", "$mdSidenav", function ($scope, appUsers, connectAdmin, $mdSidenav) {
    $scope.pageClass = "users";

    $scope.list = appUsers;

    $scope.openMenu = function () {
        $mdSidenav('left').toggle();
    };

    $scope.disconnect = function () {
        connectAdmin.disconnect();
    };
} ]);

app.controller("ShopEditorCtrl", ["$window", "$http", "$scope", "$route", "googleGeocode", "appShopEditor", "appShopCreator", "connectAdmin", "$token", "$mdBottomSheet", "$mdSidenav", "$exception", function ($window, $http, $scope, $route, googleGeocode, appShopEditor, appShopCreator, connectAdmin, $token, $mdBottomSheet, $mdSidenav, $exception) {
    $scope.viewClass = "shop";

    var shopId = $route.current.params.id;
    if (shopId) $scope.shop = appShopEditor.get(shopId);
    else $scope.shop = appShopCreator;

    $scope.shop.init().then(function(){
        $scope.locationText = $scope.shop.data.location.address;
    });

    $scope.$watch("category", function(newValue, oldValue){
        if(!newValue) return;
        $scope.shop.data.categories.push(newValue);
        $scope.category = null;
    });

    $scope.removeCategory = function (index) {
        $scope.shop.data.categories.splice(index, 1);
    };

    $scope.getLocation = function (val) {
        return googleGeocode.getLocations(val);
    };

    $scope.$watch("employee", function(newValue, oldValue){
        if(!newValue) return;
        $scope.shop.data.users.employees.push({ _id: $scope.employee._id, login: $scope.employee.login });
        $scope.employee = null;
    });

    $scope.removeEmployee = function (index) {
        $scope.shop.data.users.employees.splice(index, 1);
    };

    $scope.openBottomSheet = function (event) {
        var target = angular.element(event.target);
        var textarea = target.parent().parent().find('textarea')[0];
        var model = $scope.shop.data.description;

        $mdBottomSheet.show({
            templateUrl: '/pro/partials/bottomsheet/editor.html',
            controller: 'BottomSheetEditorCtrl',
        }).then(function(data){
            var preffix = model.content.substr(0, textarea.selectionStart);
            if (preffix.length > 0 && preffix[preffix.length - 1] != " ") preffix += " ";
            var suffix = model.content.substr(textarea.selectionEnd) || " ";
            model.content = preffix + data + suffix;
        });
    };

    $scope.back = function () {
        $window.history.back();
    };

    $scope.openMenu = function () {
        $mdSidenav('left').toggle();
    };

    $scope.disconnect = function () {
        connectAdmin.disconnect();
    };
} ]);


app.controller("ShopsCtrl", ["$scope", "appShops", "connectAdmin", "$mdSidenav", function ($scope, appShops, connectAdmin, $mdSidenav) {
    $scope.pageClass = "shops";

    $scope.list = appShops;

    $scope.openMenu = function () {
        $mdSidenav('left').toggle();
    };

    $scope.disconnect = function () {
        connectAdmin.disconnect();
    };
} ]);
